<template>
	<view>
		<MyHeaderVue></MyHeaderVue>
		<MySearchVue></MySearchVue>
		<view class="activity_box">
			<view class="item" v-for="item in shopNavList" :style="{backgroundImage:`url(${item.backgroundImage})`}">
				<view class="time" v-if="item.timestamp">
					<text>{{h}}</text>:<text>{{m}}</text>:<text>{{s}}</text>
				</view>
				<view class="title">{{item.title}}</view>
			</view>
		</view>
		<view class="banner_box">
			<image src="/static/cai.webp" mode="widthFix"></image>
		</view>
		<view class="product_box">
			<view class="product_item" v-for="(item, index) in productList" :key="index">
				<view class="item_img" style="height: 464rpx;">
					<image :src="item.img" mode="widthFix" lazy-load
						:loading="index < initialLoadCount ? 'eager' : 'lazy'"></image>
				</view>
				<view class="item_info">
					<view class="item_info_title">{{item.title}}</view>
					<view class="item_info_price">
						<view class="price">￥{{item.price}}</view>
						<view class="collect">{{item.cfav}}</view>
					</view>
					<view class="item_btn">立即购买</view>
				</view>
			</view>
		</view>
		<view class="loading-more" v-if="isLoading">
			<text>加载中...</text>
		</view>
		<view class="no-more" v-if="!hasMore && productList.length > 0">
			<text>没有更多了~</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		onPageScroll
	} from '@dcloudio/uni-app'
	import MyHeaderVue from '../../components/MyHeader/MyHeader.vue'
	import MySearchVue from '../../components/MySearch/MySearch.vue'


	const shopNavList = ref([])
	const productList = ref([])
	const currentPage = ref(1)
	const isLoading = ref(false)
	const hasMore = ref(true)
	const initialLoadCount = 6

	let time = uni.getStorageSync('time') || 10800
	const h = ref('00')
	const m = ref('00')
	const s = ref('00')


	const timeout = () => {
		time--
		h.value = parseInt(time / 60 / 60 % 24)
		h.value = h.value < 10 ? '0' + h.value : h.value
		m.value = parseInt(time / 60 % 60)
		m.value = m.value < 10 ? '0' + m.value : m.value
		s.value = parseInt(time % 60)
		s.value = s.value < 10 ? '0' + s.value : s.value
		if (time < 0) time = 10800
		uni.setStorageSync('time', time)
	}

	const getshopNav = () => {
		uni.request({
			url: 'https://apis.netstart.cn/mogujie/shopNav.json',
			success: (res) => {
				shopNavList.value = res.data || []
			}
		})
	}


	const getproduct = async (page = 1) => {
		if (isLoading.value || !hasMore.value) return;

		isLoading.value = true;
		uni.showLoading({
			title: '加载中...',
			mask: true
		});

		try {
			// 统一处理请求返回值
			const res = await new Promise((resolve, reject) => {
				uni.request({
					url: `https://apis.netstart.cn/mogujie/goods/personalized?page=${page}`,
					success: (res) => resolve(res),
					fail: (err) => reject(err)
				});
			});

			if (!res.data?.data?.wall?.docs) {
				throw new Error('返回数据格式不正确');
			}

			if (res.data.data.wall.docs.length === 0) {
				hasMore.value = false;
				return;
			}

			const newItems = res.data.data.wall.docs.map((item, index) => ({
				...item,
				immediateLoad: page === 1 || index < initialLoadCount
			}));

			productList.value = page === 1 ? newItems : [...productList.value, ...newItems];
			currentPage.value = page;
		} catch (err) {
			console.error('加载商品失败:', err);
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
			hasMore.value = false; // 出错时停止继续加载
		} finally {
			isLoading.value = false;
			uni.hideLoading();
		}
	}


	onMounted(() => {
		getshopNav()
		getproduct(1)
		setInterval(timeout, 1000)
	})


	const loadingDistance = 800
	onPageScroll((e) => {
		if (isLoading.value || !hasMore.value) return

		uni.createSelectorQuery().select('.product_box').boundingClientRect(rect => {
			const windowHeight = uni.getSystemInfoSync().windowHeight
			const distanceToBottom = rect.height - e.scrollTop - windowHeight

			if (distanceToBottom < loadingDistance) {
				getproduct(currentPage.value + 1)
			}
		}).exec()
	})
</script>

<style lang="scss">
	.activity_box {
		background-color: #fff;
		display: flex;
		flex-wrap: wrap;
		gap: 18rpx;
		align-items: center;
		box-sizing: border-box;
		padding: 18rpx;
		justify-content: start;

		.item {
			width: 165rpx;
			height: 165rpx;
			position: relative;
			background-repeat: no-repeat;
			background-size: cover;

			.time {
				position: absolute;
				bottom: 43rpx;
				color: #fff;
				display: flex;
				left: 50%;
				width: 112rpx;
				margin-left: -56rpx;
				align-items: baseline;

				text {
					background-color: #333;
					border-radius: 3rpx;
					width: 32rpx;
					height: 32rpx;
					text-align: center;
					line-height: 32rpx;
					font-size: 20rpx;
					font-weight: 700;
				}
			}

			.title {
				width: 100%;
				position: absolute;
				bottom: 4rpx;
				font-weight: 700;
				font-size: 28rpx;
				color: #fff;
				text-align: center;
			}
		}
	}

	.banner_box {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 10rpx;

		image {
			width: 100%;
		}
	}

	.product_box {
		width: 100%;
		box-sizing: border-box;
		padding: 18rpx 18rpx 120rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-around;
		gap: 18rpx;

		.product_item {
			width: calc(50% - 18rpx);
			background-color: #fff;
			border-radius: 5rpx;

			.item_img {
				border-radius: 5rpx;
				overflow: hidden;

				image {
					width: 100%;
				}
			}

			.item_info {
				padding: 10rpx 12rpx;

				.item_info_title {
					font-size: 24rpx;
					color: #333;
					text-overflow: ellipsis;
					overflow: hidden;
					text-wrap: nowrap;
					white-space: nowrap;
					height: 36rpx;
				}

				.item_info_price {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 4rpx;

					.price {
						color: #333;
						font-size: 30rpx;
						font-weight: 700;
					}

					.collect {
						padding-right: 30rpx;
						background: url('/static/collect.png') 100% no-repeat;
						color: #666;
						background-size: auto 24rpx;
						font-size: 24rpx;
					}
				}

				.item_btn {
					color: #fff;
					background-color: #ff5777;
					width: 100%;
					height: 50rpx;
					line-height: 50rpx;
					font-size: 26rpx;
					margin: 4rpx 0;
					border-radius: 6rpx;
					text-align: center;

				}
			}
		}
	}

	.loading-more,
	.no-more {
		text-align: center;
		padding: 20rpx;
		color: #999;
		font-size: 24rpx;
	}

	.loading-more {
		display: flex;
		justify-content: center;
		align-items: center;

		&::after {
			content: '';
			display: inline-block;
			width: 20rpx;
			height: 20rpx;
			margin-left: 10rpx;
			border: 3rpx solid #ddd;
			border-top-color: #ff5777;
			border-radius: 50%;
			animation: spin 0.8s linear infinite;
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
</style>